import React, { useState, useEffect } from 'react';
import { CFormInput, CFormLabel, CRow, CCol, CFormSelect, CButton, CCardTitle, CForm, CCardGroup   } from '@coreui/react';
import { CChart } from '@coreui/react-chartjs';
import { useSelector } from 'react-redux'


const Statistics = () => {
 const [statisticsData, setStatisticsData] = useState([]);
 const [message, setMessage] = useState('');
 const [chartData, setChartData] = useState([]);
 const [params, setParams] = useState({
  start_year: 2022,
  start_week: 0,
  end_year: 2024,
  end_week: 52,
  id_filename: 1,
  modality: null,
  locality: null,
});
const token = useSelector((state) => state.token);

const [inputValues, setInputValues] = useState({
  startYear: '',
  startWeek: '',
  endYear: '',
  endWeek: '',
});



const fetchData = async () => {
  let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/statistics/?start_year=${params.start_year}&start_week=${params.start_week}&end_year=${params.end_year}&end_week=${params.end_week}`;
  if (params.id_filename) {
    url += `&id_filename=${params.id_filename}`;
  }
  if (params.modality) {
    url += `&modality=${params.modality}`;
  }

  try {
    const response = await fetch(url,
      {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
      }
    );
    const data = await response.json();
    setChartData(data);
  } catch (error) {
    console.error('Ошибка при получении данных:', error);
  }
};

const fetchFilename = async () => {
  try {
    const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/statistics/filename`,
      {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
      }
    );
    const data = await response.json();
    setStatisticsData(data);
  } catch (error) {
    console.error('Ошибка при получении данных:', error);
  }
};

 useEffect(() => {
  fetchFilename();
  fetchData();
}, [params]);

  const handleFileChange = (event) => {
    const { value } = event.target;
    setParams(prevParams => ({
    ...prevParams,
      id_filename: value,
    }));
    fetchData();
  };


  const handleModalityChange = (event) => {
    const selectedModalityId = parseInt(event.target.value, 10);
    const selectedModality = modalityitems.find(item => item.id === selectedModalityId);
    if (selectedModality) {
      if (selectedModalityId === 0) {
        setParams(prevParams => ({
         ...prevParams,
          modality: null,
        }));
      } else {
        setParams(prevParams => ({
         ...prevParams,
          modality: selectedModality.name,
        }));
      }
    }
  };
  

  const handleInputChange = (e, field) => {
    setInputValues({
    ...inputValues,
      [field]: e.target.value,
    });
  };

  const handleButtonClick = () => {
    setParams({
    ...params,
      start_year: inputValues.startYear,
      start_week: inputValues.startWeek,
      end_year: inputValues.endYear,
      end_week: inputValues.endWeek,
    });
    console.log(params);
  };

  const modalityitems = [
    { id: 0, name: 'Модальность' },
    { id: 1, name: 'РГ' },
    { id: 2, name: 'КТ' },
    { id: 3, name: 'МРТ' },
    { id: 4, name: 'ММГ' },
    { id: 5, name: 'Флг' },
    { id: 6, name: 'Денс' },
    { id: 7, name: 'РХ' },
    { id: 8, name: 'НДКТ' },
    { id: 9, name: 'ПЭТ/КТ' },
  ];

  const modalityoptions = modalityitems.map(item => ({
    label: item.name,
    value: item.id.toString(),
  }));

  const handleUpload = () => {
    const file = document.getElementById('csvFile').files[0];
    if (!file) {
        setMessage('Файл не выбран');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/files/uploadfile/`, {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
      },
    })
  .then(response => response.json())
  .then(data => {
        setMessage(data.msg || data.detail);
        fetchFilename()
    })
  .catch(error => {
        console.error('Ошибка при загрузке файла', error);
    });
  };


 return (
  <>
  <h1>Статистика</h1>
  <br></br>
  <CRow>
    <CCol xs={4}>
      <CFormLabel>Файл статистики</CFormLabel>
      <CFormSelect 
        aria-label="Выберите файл статистики"
        options={statisticsData.map(item => ({
          label: item.filename,
          value: item.id.toString(),
        }))}
        onChange={handleFileChange}
      />
      <br></br>
      <CRow>
        <CCol xs={9}>
          
        </CCol>
        <CCol xs={3}>
          
          
        </CCol>
      </CRow>
    </CCol>
    <CCol xs={2}></CCol>
    <CCol xs={6}>
      <CRow>
        <CCol>
          <CCardTitle as="h6">Начало периода</CCardTitle>
        </CCol>
        <CCol>
          <CFormInput
            type="text"
            size="sm"
            placeholder="Год"
            aria-label="sm input example"
            onChange={(e) => handleInputChange(e, 'startYear')}
          />
        </CCol>
        <CCol>
          <CFormInput
            type="text"
            size="sm"
            placeholder="Номер недели"
            aria-label="sm input example"
            onChange={(e) => handleInputChange(e, 'startWeek')}
          />
        </CCol>
      </CRow>
      <br></br>
      <CRow>
        <CCol>
          <CCardTitle as="h6">Конец периода</CCardTitle>
        </CCol>
        <CCol>
          <CFormInput
            type="text"
            size="sm"
            placeholder="Год"
            aria-label="sm input example"
            onChange={(e) => handleInputChange(e, 'endYear')}
          />
          </CCol>
          <CCol>
           <CFormInput
              type="text"
              size="sm"
              placeholder="Номер недели"
              aria-label="sm input example"
              onChange={(e) => handleInputChange(e, 'endWeek')}
            />
          </CCol>
      </CRow>
      <br></br>
      <CRow>
        <CCol xs={9}>

        </CCol>
        <CCol xs={3}>
          
        </CCol>
      </CRow>
      
    </CCol>
    
  </CRow>
  <br></br>
  <CRow>
    <CCol xs={5}>
      <CForm>
            <CFormLabel htmlFor="csvFile">Выберите CSV файл со статистикой</CFormLabel>
            <CFormInput type="file" id="csvFile" accept=".csv" size="sm"/>
            {message && <p>{message}</p>}
          </CForm>
    </CCol>
    <CCol xs={5}>
    <CButton onClick={handleUpload} color="light" variant="outline" className='mt-4'>
            Загрузить
          </CButton>
    </CCol>
    <CCol xs={2}>
    <CButton
            color="light"
            variant="outline"
            className='mt-4'
            onClick={handleButtonClick}
            >
            Применить
          </CButton>
    </CCol>
  </CRow>
  <br></br>
  <CRow>
    <CCol xs={6}>
      <CFormSelect 
        aria-label="Default select example"
        options={modalityoptions}
        onChange={handleModalityChange}
      />
    </CCol>
  </CRow>
  <CRow>
  <CChart
      type="bar"
      data={chartData}
      options={{
        responsive: true,
        stacked: true,
        scales: {
          x: {
            stacked: true,
          },
          
          y: {
            stacked: true,
          }
        }
      }}
    />
  </CRow>
  </>
 );
};

export default Statistics;
